﻿using Factory.MasterData.WorkStations.Dto;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

using ZXing;
using ZXing.Common;
using System.Drawing;
using System.IO;
using Factory.MasterData.WorkshopSetups;
using System.Diagnostics;
using System.Linq.Dynamic.Core;
using Factory.Common;
using CSRedis;
using Redis.Cluster.Demo;

namespace Factory.MasterData.WorkStations
{
    /// <summary>
    /// 实现工作站接口
    /// </summary>
    public class WorkStationAppService : IApplicationService, IWorkStationAppService
    {
        /// <summary>
        /// 工作站仓储
        /// </summary>
        private readonly IRepository<WorkStation, int> _workStationRepository;
        private readonly IRepository<WorkshopSetup, int> _workshopSetupsRepository;

        //private readonly CSRedisClient _redisHelper = new CSRedisClient("127.0.0.1:6379");

        public WorkStationAppService(IRepository<WorkStation, int> workStationRepository,IRepository<WorkshopSetup, int> workshopSetupsRepository)
        {
            _workStationRepository = workStationRepository;
            _workshopSetupsRepository = workshopSetupsRepository;
        }


        /// <summary>
        /// 获取工作站（分页）
        /// </summary>
        /// <param name="workStationName">工作站名称</param>
        /// <param name="isNo">是否删除</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <returns></returns>
        public async Task<PagedResult> GetWorkStationShow(string? workStationName, int isNo, int page=1, int limit=10)
        {

            var workstationList = from a in _workStationRepository.GetListAsync().Result
                      join b in _workshopSetupsRepository.GetListAsync().Result
                      on a.WorkshopId equals b.Id
                      where a.IsNo == isNo 
                      select new WorkStationShowDto
                      {
                          Id = a.Id,
                          WorkStationCode = a.WorkStationCode,
                          WorkStationName = a.WorkStationName,
                          WorkStationLocations = a.WorkStationLocations,
                          WorkshopId = a.WorkshopId,
                          ProcessId = a.ProcessId,
                          IsNo = a.IsNo,
                          remark = a.remark,
                          Image = a.Image,
                          WorkshopName = b.WorkShopName,
                          ProcessName = "sss"
                      };
            workstationList = workstationList.WhereIf(!string.IsNullOrEmpty(workStationName), m => m.WorkStationName.Contains(workStationName));

            var pagedResult = new PagedResult
            {
                RowCount = page,
                PageCount = limit,
                CurrentPage = workstationList.Count(),
                Queryable = workstationList.Skip((page - 1) * limit).Take(limit).ToList().AsQueryable()
            };

            return await Task.FromResult(pagedResult);
        }



        private static object obj = new object();

        /// <summary>
        /// 获取车间的数据
        /// </summary>
        /// <returns></returns>
        public  List<WorkshopSetupsListDto> WorkshopSetupsList()
        {
            //根据Key值，获取学生list集合
            var workstationList = RedisClusterHelper.Get<List<WorkshopSetupsListDto>>("Car");
            if (workstationList == null)
            {
                lock (obj)
                {
                    if (workstationList == null)
                    {
                        var workshopsetupsListDto =  _workshopSetupsRepository.GetListAsync().Result;

                        workstationList = workshopsetupsListDto.Select(a => new WorkshopSetupsListDto
                        {
                            Id = a.Id,
                            WorkShopName = a.WorkShopName,
                        }).ToList();
                        
                        //将学生集合缓存在Redis中，key值为：StudentList
                        RedisClusterHelper.Set("Car", workstationList, DateTime.Now.AddDays(1));
                    }
                }
            }
            return workstationList;

        }

        /// <summary>
        /// 新增工作站
        /// </summary>
        /// <param name="input">工作站实体</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> AddWorkStation(WorkStation workstation)
        {
            var workStationData = await _workStationRepository.GetQueryableAsync(); 
            if (workStationData.Any(x => x.WorkStationName == workstation.WorkStationName))
            {
                // 工作站名称已存在
                return -1;
            }
            await _workStationRepository.InsertAsync(workstation);
            return 1; // 返回成功标识
        }

        /// <summary>
        /// 获取车间具体数据
        /// </summary>
        /// <returns>返回对应数据</returns>
        public async Task<WorkStation> SpecificData(int id)
        {
            // 使用 await 直接获取结果
            var workStation = await _workStationRepository.FindAsync(id);

            // 进行 null 检查，如果需要的话
            if (workStation == null)
            {
                // 可以抛出异常或其他合适的处理方式
                throw new Exception($"WorkStation with id {id} not found.");
            }

            return workStation;
        }



        /// <summary>
        /// 删除工作站
        /// </summary>
        /// <param name="id"></param>
        /// <returns>返回受影响数据</returns>
        public async Task<int> DeleteWorkStation(int id)
        {
            var data = await _workStationRepository.FindAsync(id);
            data.IsNo = 0; // 根据你的逻辑设置 IsNo

            await _workStationRepository.UpdateAsync(data);

            return 1; 
        }


        /// <summary>
        /// 修改工作站
        /// </summary>
        /// <param name="input">工作站DTO</param>
        /// <returns>返回受影响数据</returns>
        public async Task<int> UpdateWorkStation(WorkStationInputAddDto addDto)
        {
            // 检查是否存在重复的工作站
            var isDuplicate = await _workStationRepository.FindAsync(x => (x.WorkStationCode == addDto.WorkStationCode && x.Id != addDto.Id) || (x.WorkStationName == addDto.WorkStationName && x.Id != addDto.Id));

            if (isDuplicate != null)
            {
                return 1; // 返回特定的状态码以表示重复
            }

            // 映射并更新工作站
            var workstation = AutoMapperExt.MapTo<WorkStation>(addDto);
            await _workStationRepository.UpdateAsync(workstation);

            return 1; // 或者根据实际情况返回受影响的行数


        }

    }
}
